package handler

import (
	"app-box/config"
	"io/ioutil"
	"net/http"
	"path/filepath"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/render"
)

type StaticResourceHandler struct {
	Path string // 静态资源文件夹
}

func (h StaticResourceHandler) InitRoute(route *gin.Engine) {
	route.StaticFS("/", http.Dir(h.Path))
	if config.Server.SupportVueRoteHistoryMode {
		route.NoRoute(func(ctx *gin.Context) {
			content, err := ioutil.ReadFile(filepath.Join(h.Path, "index.html"))
			if err != nil {
				ctx.String(http.StatusNotFound, "404 not found !!")
				return
			}
			ctx.Render(http.StatusOK, render.Data{ContentType: "text/html; charset=utf-8", Data: content})
		})
	} else if config.Server.NotfoundPagePath != "" {
		route.NoRoute(func(ctx *gin.Context) {
			ctx.FileFromFS(config.Server.NotfoundPagePath, http.Dir(h.Path))
		})
	} else {
		route.NoRoute(func(ctx *gin.Context) {
			ctx.String(http.StatusNotFound, "404 not found !!")
		})
	}
}
